package com.htt.app.babau.adapter;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.htt.app.babau.ListActivity;
import com.htt.app.babau.R;
import com.htt.app.babau.config.Config;
import com.htt.app.babau.objects.Categories;
import com.htt.app.babau.task.LoadImageAssets;

public class MainGridAdapter extends BaseAdapter {
	private List<Categories> data = null;
	private Context context;
	private LayoutInflater inflater;
	private AssetManager assetManager = null;
	
	public MainGridAdapter(Context context, List<Categories> list) {
		this.context = context;
		data = list;
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		assetManager = context.getAssets();
	}
	
	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View v = convertView;
		ViewHolder holder;
		if(convertView == null) {
			v = inflater.inflate(R.layout.main_item, null);
			holder = new ViewHolder();
			holder.textView = (TextView) v.findViewById(R.id.main_item_title);
			holder.imageView = (ImageView) v.findViewById(R.id.main_item_image);
			
			v.setTag(holder);
		} else {
			holder = (ViewHolder) v.getTag();
		}
		
		holder.textView.setText(data.get(position).getName());
		holder.imageView.setLayoutParams(new RelativeLayout.LayoutParams(
				Config.IMAGE_WIDTH, Config.IMAGE_HEIGHT));

		LoadImageAssets loadImage = new LoadImageAssets(assetManager, holder.imageView, 
				data.get(position).getImage());
		loadImage.execute();
		
		v.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(context, ListActivity.class);
				intent.putExtra("id", data.get(position).getId());
				intent.putExtra("title", data.get(position).getName());
				context.startActivity(intent);
			}
		});
		
		return v;
	}

	public static class ViewHolder {
		TextView textView;
		ImageView imageView;
	}
	
	
}
